clear all
%Read Swap rates and credit spreads from Input file
DataSwapRates=xlsread('PilotPortfolio.xls',6);
DataCreditSpreads=xlsread('PilotPortfolio.xls',7);
%Build Discount factors for Maturities in months
%[ DiscountFactor,CSDaysofMonths,DiscountCreditFactor] = GenerateDiscountFactors(DataSwapRates,DataCreditSpreads);
NumberOfSimulation=100000;
R=.21;
DataTransition=xlsread('PilotPortfolio.xls',1);
TransitionMatrix=DataTransition(2:end,2:end);
[ExposureData,Dates]=xlsread('PilotPortfolio.xls',3);
ExposureCommit=ExposureData(1:end,2);
OffBalanceExposure=ExposureData(1:end,14);
ExposureCreditRating=ExposureData(1:end,3);
PositionIndustry=ExposureData(1:end,6);%25
PositionGeo=ExposureData(1:end,7);%75
ExposureLGD=ExposureData(:,9);
ExposureLEQ=ExposureData(:,13);
NumberOfExposures=length(ExposureCommit);
EAD=ExposureCommit+ExposureLEQ.*OffBalanceExposure;
CovarianceData=xlsread('PilotPortfolio.xls',5);
FactorVolatility=CovarianceData(3:end,4);
FactorCorrelation=CovarianceData(3:end,5:28);
%Generate Covariance Matrix 
FactorCovariance=diag(FactorVolatility)*FactorCorrelation*...
 diag(FactorVolatility);
%FactorCovariance=FactorCorrelation;
%Initiate weight Matrix at zeros 
FactorWeights=zeros(NumberOfExposures,24);
Loss=-EAD.*ExposureLGD;
%EL=mean(EAD.*ExposureLGD.*TransitionMatrix(ExposureCreditRating,end))
%Generate Thresholds for Transitions
RatingThresholds=norminv(TransitionMatrix(:,end));
ThresholdTable=RatingThresholds(ExposureCreditRating);

for i=1:NumberOfExposures
    FactorWeights(i,PositionIndustry(i))=.25;
    FactorWeights(i,PositionGeo(i))=.75;    
    VolatilityZ(i,1)=sqrt(FactorWeights(i,:)*...
        FactorCovariance*FactorWeights(i,:)');
 end
tic
for j=1:10000
    Factors=mvnrnd(zeros(1,24),FactorCovariance,1);
    Z=sum(repmat(Factors,NumberOfExposures,1).*FactorWeights,2);
    ZTilda=Z./VolatilityZ;  
    X=R*ZTilda+sqrt(1-R^2)*randn(NumberOfExposures,1);    
    L(j)=sum(Loss(X<ThresholdTable));   
end
toc








